import { updateStorage } from './tools'


// 获取本地存储数据
let cartlist = localStorage.getItem('cartlist')
try {
    cartlist = JSON.parse(cartlist) || []
} catch (err) {
    cartlist = []
}

export default {
    // 启用命名空间
    namespaced: true,
    state: {
        cartlist,
    },
    getters: {

    },
    mutations: {
        // 购物车获取添加至本地
        addToLocal(state, payload) {
            state.cartlist = payload;
            updateStorage('cartlist', state.cartlist)
        },
        // 添加商品至本地购物车
        addGoodToCart(state, payload) {
            state.cartlist.push(payload);
            updateStorage('cartlist', state.cartlist)
        },
        // 删除商品
        removeFromCart(state, ids) {
            state.cartlist = state.cartlist.filter(item => {
                return !ids.includes(item.goods_id)
            })
            updateStorage('cartlist', state.cartlist)
        },
        // 数量修改
        changeQty(state, payload) {
            state.cartlist.forEach(item => {
                if (item.goods_id == payload.goods_id) {
                    item.Cartcount = payload.Cartcount;
                }
            })
            updateStorage('cartlist', state.cartlist);
        },
        //全选
        checkAll(state, payload) {
            state.cartlist.forEach(item => {
                item.is_select = payload
            })
            updateStorage('cartlist', state.cartlist);

        },
        // 修改单个是否选择
        checkOne(state, payload) {
            state.cartlist.forEach(item => {
                if (item.goods_id == payload.id) {
                    item.is_select = payload.checked;
                }
            })
            updateStorage('cartlist', state.cartlist);

        },
    },
    actions: {

    }
}